import { Injectable } from '@nestjs/common';
import { Logger } from 'log4js';

import { appLog, businessLog, cacheLog, databaseLog, errorLog, httpLog, perfLog } from '@/common/log4js.config';
import { getCurrentContext } from '@/common/async-context';

@Injectable()
export class LoggingService {
    constructor() {}
    /**
     * 自动获取当前上下文并设置到日志器
     */
    private setContextToLogger(logger: Logger): void {
        const context = getCurrentContext();
        if (context) {
            logger.addContext('traceId', context.traceId);
            logger.addContext('uri', context.uri);
        }
    }

    /**
     * 应用日志
     */
    app(message: string, ...args: any[]): void {
        this.setContextToLogger(appLog);
        appLog.info(message, ...args);
    }

    /**
     * 错误日志
     */
    error(message: string, error?: Error, ...args: any[]): void {
        this.setContextToLogger(errorLog);
        errorLog.error(message, args);
    }

    /**
     * 数据库日志
     */
    database(message: string, ...args: any[]): void {
        this.setContextToLogger(databaseLog);
        databaseLog.info(message, args);
    }

    /**
     * 缓存日志
     */
    cache(message: string, ...args: any[]): void {
        this.setContextToLogger(cacheLog);
        cacheLog.info(message, args);
    }

    /**
     * 性能日志
     */
    perf(message: string, ...args: any[]): void {
        this.setContextToLogger(perfLog);
        perfLog.info(message, args);
    }

    /**
     * 缓存日志
     */
    http(message: string, ...args: any[]): void {
        this.setContextToLogger(httpLog);
        httpLog.info(message, args[0]);
    }

    /**
     * 业务日志
     */
    business(message: string, ...args: any[]): void {
        this.setContextToLogger(businessLog);
        businessLog.info(message, args);
    }
}
